import React from 'react';
import './login.less';
import logo from '../../assets/images/logo.jpg';
import { Form, Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { reqLogin } from "../../api/index.js";
import { handleRes } from "../../api/handle.js";
import { useHistory, Redirect } from "react-router-dom";
import { memoryUtils } from "../../utils/memoryUtils";
import storageUtils from "../../utils/storageUtils.js";


export const Login = () => {
    const user = memoryUtils.user;
    if(user.username) {
        return <Redirect to="/"/>
    }
    return (
        <div className="login">
            <header className="login-header">
                <img src={logo} alt={logo}></img>
                <h1>React：后台管理项目</h1>
            </header>
            <section className="login-content">
                <h2>用户登录</h2>
                <NormalLoginForm/>
            </section>
        </div>
    )
}


const NormalLoginForm = () => {
    const [form] = Form.useForm();
    const history = useHistory();
    const handleClick = async () => {
        const {username, password} = form.getFieldsValue();
        const res = await reqLogin(username, password);
        if(handleRes(res)) {
            memoryUtils.user = res.data;
            storageUtils.saveUser(res.data);
            history.replace("/");
        }
    }
    
    return (
        <Form scrollToFirstError="true" form={form} onFinish={handleClick} className="login-form">
            <Form.Item name="username" rules={[
                { required: true, whitespace: true, message: "Please input your username!"},
                { max: 16, message: "username is too long"},
                { min: 4, message: "username is too short"},
                { pattern: /^[a-zA-Z0-9_]+$/, message: "username is invalid"}]} >
                <Input prefix={<UserOutlined type="user" style={{ color: "rgba(0,0,0,.25)" }} />} placeholder="Username" />
            </Form.Item>
            <Form.Item name="password" rules={[{required: true, message: "Please input your password!"}]}>
                <Input.Password prefix={<LockOutlined type="lock" style={{ color: "rgba(0,0,0,.25)" }} />} placeholder="Password" />
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
            </Form.Item>
        </Form>
    )
}
